//
//  HMLoginViewController.m
//  HMSdkDemo
//
//  Created by smarthome on 16/4/14.
//  Copyright © 2016年 smarthome. All rights reserved.
//

#import "HMLoginViewController.h"
#import "UIViewController+HM.h"
#import "HMCreateFamilyVC.h"


#define UserDefaults  [NSUserDefaults standardUserDefaults]

@interface HMLoginViewController()

@property (strong, nonatomic) IBOutlet UITextField *accountTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;

@end

@implementation HMLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTouchAction];
    
    [self getUserNameAndPassword];
}

-(void)getUserNameAndPassword
{
    NSString *userName = [UserDefaults objectForKey:@"hm_userName"];
    NSString *password = [UserDefaults objectForKey:@"hm_password"];
    
    _accountTextField.text = userName;
    _passwordTextField.text = password;
}
-(void)saveUserName:(NSString *)userName password:(NSString *)password
{
    if (userName && password) {
        [UserDefaults setObject:userName forKey:@"hm_userName"];
        [UserDefaults setObject:password forKey:@"hm_password"];
    }
}

#pragma mark - 登录

- (IBAction)login:(id)sender {
    
    [_accountTextField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
    
    if (_accountTextField.text.length == 0
        || _passwordTextField.text.length < 6
        || _passwordTextField.text.length > 12){
        
        return;
    }
    
    NSString *account = _accountTextField.text;
    NSString *password = _passwordTextField.text;
    
    [self saveUserName:account password:password];
    
    [HMSDK loginWithUserName:account password:password completion:^(KReturnValue value) {
        if (value == KReturnValueSuccess) {
            DLog(@"登录成功");
            [self performSegueWithIdentifier:@"loginSuccess" sender:nil];
        }else if (value == KReturnValueFamilyEmpty){
            DLog(@"请先创建家庭");
            HMCreateFamilyVC *createFamilyVc = [[HMCreateFamilyVC alloc]init];
            [self.navigationController pushViewController:createFamilyVc animated:YES];
        }
        else {
            DLog(@"登录失败");
            [self popAlertWithMessage:@"登录失败"];
        }
    }];
}

@end
